package cn.steam.foo.util.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zhang jintao on 2022/05/19
 **/
@Service
@Slf4j
public class RedisLock implements Lock {

    private static final String OK = "ok";

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean tryLock(String key) {
        throw new RuntimeException("RedisLock尚未实现该方法");
    }

    @Override
    public boolean lock(String key) {
        try {
            Boolean result = redisTemplate.opsForValue().setIfAbsent(key, OK);
            return result != null && result;
        } catch (Exception e) {
            log.error("获取分布式锁失败，redis操作异常,key:{}:", key, e);
            return false;
        }
    }

    @Override
    public boolean lock(String key, int timeout, TimeUnit timeUnit) {
        try {
            Boolean result = redisTemplate.opsForValue().setIfAbsent(key, OK, timeout, timeUnit);
            return result != null && result;
        } catch (Exception e) {
            log.error("获取分布式锁失败，redis操作异常,key:{}:", key, e);
            return false;
        }
    }

    @Override
    public void unlock(String key) {
        try {
            Boolean delete = redisTemplate.delete(key);
            if (delete == null || !delete) {
                log.error("释放分布式失败,key:{}：", key);
            }
        } catch (Exception e) {
            log.error("释放分布式失败,key:{}：", key, e);
        }

    }
}
